<template>
  <div class="tinymce-editor">
    <editor
      ref="tinymceEditor"
      v-if="!reloading"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"
    ></editor>
  </div>
</template>

<script>
  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/print'
  import 'tinymce/plugins/preview'
  import 'tinymce/plugins/searchreplace'
  import 'tinymce/plugins/autolink'
  import 'tinymce/plugins/directionality'
  import 'tinymce/plugins/visualblocks'
  import 'tinymce/plugins/visualchars'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/plugins/template'
  import 'tinymce/plugins/codesample'
  import 'tinymce/plugins/charmap'
  import 'tinymce/plugins/autoresize'
  import 'tinymce/plugins/hr'
  import 'tinymce/plugins/pagebreak'
  import 'tinymce/plugins/nonbreaking'
  import 'tinymce/plugins/anchor'
  import 'tinymce/plugins/insertdatetime'
  import 'tinymce/plugins/advlist'
  import 'tinymce/plugins/imagetools'
  import 'tinymce/plugins/textpattern'
  import 'tinymce/plugins/help'
  import 'tinymce/plugins/autosave'
  import 'tinymce/plugins/code'

  import '../../../public/tinymce/plugins/searchreplace/plugin.min'
  import '../../../public/tinymce/plugins/layout/plugin.min'
  import '../../../public/tinymce/plugins/letterspacing/plugin.min'
  import '../../../public/tinymce/plugins/indent2em/plugin.min'
  import '../../../public/tinymce/plugins/formatpainter/plugin.min'

  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'

  import 'tinymce/icons/default'
  import { uploadAction, getFileAccessHttpUrl } from '@/api/manage'

  export default {
    components: {
      Editor
    },
    props: {
      value: {
        type: String,
        required: false
      },
      triggerChange: {
        type: Boolean,
        default: false,
        required: false
      },
      disabled: {
        type: Boolean,
        default: false
      },
      plugins: {
        type: [String, Array],
        default:
          'print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help autosave indent2em autoresize formatpainter letterspacing layout searchreplace code'
      },
      toolbar: {
        type: [String, Array],
        default:
          'fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor| bold italic underline strikethrough | link anchor | alignleft aligncenter alignright alignjustify | outdent indent |indent2em lineheight  letterspacing|' +
          '                     formatselect | fontselect | fontsizeselect | bullist numlist | blockquote subscript superscript|' +
          '                     table |image media |hr pagebreak | charmap |insertdatetime |print |preview code|layout|searchreplace| formatpainter removeformat',
        branding: false
      },
      maxHeight: {
        type: Number,
        default: 0,
        required: false
      },
      minHeight: {
        type: Number,
        default: 0,
        required: false
      }
    },
    data() {
      return {
        // 初始化配置
        init: {
          language_url: '/tinymce/langs/zh_CN.js',
          language: 'zh_CN',
          skin_url: '/tinymce/skins/lightgray',
          height: 300,
          plugins: this.plugins,
          toolbar: this.toolbar,
          max_height: this.maxHeight,
          min_height: this.minHeight,
          branding: false,
          menubar: false,
          toolbar_drawer: false,
          lineheight_formats: '1 1.1 1.2 1.3 1.4 1.5 2 28pt 30pt 31pt 32pt',
          fontsize_formats: '12px 14px 16px 18px 20px 21px 24px 36px 48px 56px 72px',
          font_formats:
            '仿宋_GB2312=仿宋_GB2312;楷体_GB2312=楷体_GB2312;黑体=SimHei;隶书=隶书;幼圆=幼圆;仿宋体=FangSong;宋体=simsun,serif;微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC;苹果苹方=PingFang SC,Microsoft YaHei;',
          images_upload_handler: (blobInfo, success) => {
            let formData = new FormData()
            formData.append('file', blobInfo.blob(), blobInfo.filename())
            formData.append('biz', 'jeditor')
            formData.append('jeditor', '1')
            uploadAction(window._CONFIG['domianURL'] + '/sys/common/upload', formData).then(res => {
              if (res.success) {
                if (res.message == 'local') {
                  const img = 'data:image/jpeg;base64,' + blobInfo.base64()
                  success(img)
                } else {
                  let img = getFileAccessHttpUrl(res.message)
                  success(img)
                }
              }
            })
          }
        },
        myValue: this.value,
        reloading: false
      }
    },
    mounted() {
      // 当JEditor在v-show时不是第一个显示时，高度会异常小（还有aTab也有这个毛病）
      // 此时只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
      this.reload()
    },
    methods: {
      reload() {
        this.reloading = true
        this.$nextTick(() => (this.reloading = false))
      },

      onClick(e) {
        this.$emit('onClick', e, tinymce)
      },
      // 可以添加一些自己的自定义事件，如清空内容
      clear() {
        this.myValue = ''
      },

      getContent(formart) {
        if (!this.$refs.tinymceEditor || !this.$refs.tinymceEditor.editor) return null
        return this.$refs.tinymceEditor.editor.getContent(formart)
      },
      resetContent() {
        this.$refs.tinymceEditor && this.$refs.tinymceEditor.editor.resetContent()
      },
      setContent(val, args) {
        this.$refs.tinymceEditor && this.$refs.tinymceEditor.editor.setContent(val, args)
      }
    },
    watch: {
      value(newValue) {
        this.myValue = newValue == null ? '' : newValue
      },
      myValue(newValue) {
        if (this.triggerChange) {
          this.$emit('change', newValue)
        } else {
          this.$emit('input', newValue)
        }
      }
    }
  }
</script>
<style scoped></style>
